// import $axios from 'axios'
import qs from 'qs';
// const host = 'https://release.zhen-yee.com';
// const host = 'http://zhenyi.asuscomm.com:9094';
const host = 'http://192.168.199.115:9090';

const event = weex.requireModule('event');

var utils = {
    requestAuth: function(url, params, success, fail, complete) {
        var token = '';
        event.getToken('', data => {
            token = data;
        })
        if (token == '') {
            event.onPush(JSON.stringify({
                path: 'login'
            }))
            return
        }
        this.request(url, params, success, fail, complete)
    },
    request: function(url, params, success, fail, complete) {
        // axios.post(url, qs.stringify(params))
        //     .then(res => {
        //         if (res.data.status == 200) {
        //             if (success) {
        //                 success(res.data);
        //             }
        //         } else {
        //             if (fail) {
        //                 fail(res.data);
        //             }
        //             console.log(res.data);
        //         }
        //     })
        //     .catch(err => {
        //         console.log(err);
        //         if (fail) {
        //             fail(err);
        //         }
        //     })
        //     .then(() => {
        //         if (complete) {
        //             complete();
        //         }
        //     });
        // const body = JSON.stringify({title, article});
        const stream = weex.requireModule('stream');
        url = host + url;
        if (params == null) {
            params = {};
        }
        params.appId = 'KaYz1G87'; // 植绘 zhenyi appid
        // params.appId = 'DoeqKYNP'; // 有趣 zhenyi appid
        var token = '';
        event.getToken('', data => {
            token = data;
        })
        params.token = token;
        // params.openId = 'oc2ls5ehaHUgNAyUTTiK_fDVZh9w';
        var timestamp = String(this.accDiv(new Date().getTime(), 1000));
        if (timestamp.indexOf(".") >= 0) {
            timestamp = timestamp.split(".")[0];
        }
        params.version = '';
        params.timestamp = timestamp;
        params.sign = this.genSign(params);

        console.log('url: ' + url + ' params: ' + JSON.stringify(params))
        // console.log('')
        stream.fetch({
            method: 'POST',
            url: url,
            type: 'json',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: qs.stringify(params)
        }, res => {
            // if (res.data && res.data.status == 200) {
            //     if (success) {
            //         success(res.data);
            //     }
            // } else {
            //     if (fail) {
            //         fail(res.data);
            //     }
            //     console.log(res.data);
            // }
            if (res.ok) {
                if (success) {
                    success(res.data);
                }
            } else if (res.status == 401) {
                event.onPush(JSON.stringify({
                    path: 'login'
                }))
            } else {
                if (fail) {
                    fail(res.data);
                }
                // console.log(res.data);
            }
            if (complete) {
                complete();
            }
        })
    },
    genSign: function(params) {
        var md5 = require('md5');

        var keys = new Array;
        for (var key in params) {
            keys.push(key);
        }
        keys.sort();

        var result = '';
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            var value = params[key];
            if (key == 'sign' || key == 'token' || key == 'str' || key == 'version') {
                continue;
            }
            if (!value) {
                continue;
            }
            result += key + '=' + value + '&';
        }
        return md5(result);
    },
    accMul: function(arg1, arg2) {
        var m = 0,
            s1 = arg1.toString(),
            s2 = arg2.toString();
        try { m += s1.split(".")[1].length } catch (e) {};
        try { m += s2.split(".")[1].length } catch (e) {};
        return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
    },
    accDiv: function(arg1, arg2) {
        var t1 = 0,
            t2 = 0,
            r1, r2;
        try { t1 = arg1.toString().split(".")[1].length; } catch (e) {}
        try { t2 = arg2.toString().split(".")[1].length; } catch (e) {}
        // with (Math) {
        r1 = Number(arg1.toString().replace(".", ""));
        r2 = Number(arg2.toString().replace(".", ""));
        return (r1 / r2) * Math.pow(10, t2 - t1);
        // }
    },
    push: function(url, params) {},
    pop: function() {},
    initData: function() {},
    setTitle: function(title) {},
    checkToken: function() {
        var token = '';
        event.getToken('', data => {
            token = data;
        })
        if (token == '') {
            event.onHome("", function(json) {
                event.onPresent(JSON.stringify({
                    path: 'login'
                }))
            })
            console.log('not auth')
            return false;
        } else {
            console.log('already login')
            return true;
        }
    }
}
export default utils